<?
class DocAdminAction extends Action {
  private $_dev = 0;
  function _initialize() {
    header('content-Type=text/html;charset=utf-8');
    $this->_dev = C("DEV_FLAG");
    if (ACTION_NAME != "login") {
      $this->checkLogin();
    }
  }

  public function checkLogin() {
    if ($_SESSION['user_name'] != "ehs" && $_SESSION['password'] != "ehscn") {
      $this->redirect('DocAdmin/login','',2,'您还没有登陆，请重新登陆，页面跳转中~');
    }
  }


  public function index() {
    $rt = array();
    $urlDoc = "E:\\www\\admin_temp_doc";
    if ($this->_dev == 1) $urlDoc = 'f:/temp_doc' ;
    //$type = array(0=>"doc,docx",1=>"ppt,pptx",2=>"xls,xlsx",3=>"pot,potx",4=>"pps",5=>"vsd",6=>"pub",7=>"mpp",8=>"rtf",9=>"pdf",10=>"txt");
    $d = dir($urlDoc);
    $i = 0;
    while(FALSE !== ($item = $d->read())) {
      if('.' ==$item || '..'==$item) {
        continue;
      }
      if(is_file($urlDoc . '/' .$item)) {
        $rt["list"][$i]["file_size"] = filesize($urlDoc . '/' .$item);
        $item = mysql_escape_string(mb_convert_encoding($item,'utf-8','gbk'));
        $docName	= $urlDoc . '\\' .$item;
        $title  = explode(".", $item);
        $title = $title[0];
        $rt["list"][$i]["title"] = $title;
        $rt["list"][$i]["file_url"] = $docName;
        $rt["list"][$i]["file_info"] = $title;
        $i++;
        if ($i > 10) break;
      }
    }

    $this->assign("info", $rt);
    $this->display();
  }

  /*  登陆  */
  public function login() {
    if ($_POST['user_name'] == "ehs" && $_POST['password'] == "ehscn") {
      $_SESSION['user_name'] = "ehs";
      $_SESSION['password'] = "ehscn";
      $this->redirect('DocAdmin/index', '', 2, "登陆成功，页面跳转中~~~");
    }else {
      $this->display();
    }
  }

  public function docList() {
    $m = M();
    import("@.ORG.Page"); //导入分页类
    $records = 20;//每页多少条记录
    $seleceCount = "select count(*) ";
    $select = "select t1.*,ifnull(t2.title,'') as hy_title,ifnull(t3.title,'') as zy_title, t4.name as type_name ";
    $from = "from a_doc t1 left join a_hy t2 on (t2.id = t1.hy_id) left join a_zy t3 on (t3.id = t1.zy_id) left join a_doc_type t4 on (t4.id = t1.type_id) ";
    /*$where = "where t1.owner_id = 1 and (t1.hy_id=0 or t1.zy_id = 0)";*/
	//echo $seleceCount.$from.$where;
    $count = $m->query($seleceCount.$from.$where);
    $count = $count[0]['count(*)'];
    $p = new Page ($count,$records);
    $p->setConfig('header','篇记录');
    $p->setConfig('prev',"上一页");
    $p->setConfig('next','下一页');
    $p->setConfig('first','<<');
    $p->setConfig('last','>>');
    $page = $p->show ();
    $limit = " limit ".$p->firstRow.','.$p->listRows;
    $list = $m->query($select.$from.$where.$limit);
	$selfURL = urlencode(str_replace(array('?','/'),array('~','_'),__SELF__));
	
	$this->assign("selfURL", $selfURL);
    $this->assign("info", $list);
    $this->assign("nowPage",$p->nowPage);
    $this->assign("page", $page );
    $this->assign("records",$records);
    $hz = $this->_getHZRList(array("a_hy","a_zy"));
    $this->assign("hz", $hz);
    $this->display('list');
  }

  private function _getHZRList($table) {
    $m = M();
    $rt = array();
    foreach ($table as $k => $v) {
      $list = $m->query("select * from $v");
	  $rt[$k] = $this->_reList(array(),$list,0);
    }
    return $rt;
  }

  private function _reList($rt,$list,$did) {
    foreach ($list as $k => $v) {
      if ($did == $v["did"]) {
        $rt[$k] = array(id=>$v["id"],title=>$v["title"],law_count=>$v['law_count'],dwon_line_ids=>array(),downLine=>array());
        $rt[$k]["downLine"] = $this->_reList(array(),$list,$v['id']);
        foreach ($rt[$k]["downLine"] as $key => $value) {
          $rt[$k]["dwon_line_ids"][] = $value['id'];
        }
      }
    }
    return $rt;
  }

  public function edit() {
	  if(empty($_POST['title'])){
		  if(!empty($_GET['id'])){
			  $m = M('ADoc');
			  $bakURL = empty($_GET['bakURL'])?'':$_GET['bakURL'];
			  $doc = $m->find((int)$_GET['id']);
			  $zyList = $this->_getZyList();
			  $hyList = $this->_getHyList();
			  /*$appList = $this->_getAppList();*/
			  $typeList = $this->_getTypeList();
			  $this->assign('zyList', $zyList);
			  $this->assign('hyList', $hyList);
			  //ump($appList);
			  $this->assign('typeList', $typeList);
			  /*$this->assign('appList', $appList);*/
			  $this->assign('bakURL', $bakURL);
			  $this->assign('doc', $doc);
			  $this->display();
		  } else {
			  $this->error('参数错误');
		  }
	  } else {
		  if(empty($_POST['id']) || empty($_POST['title'])|| empty($_POST['zy_id'])|| empty($_POST['hy_id'])|| empty($_POST['type_id'])){
			 $this->error('参数错误'); 
		  } else {
			 $m = M('ADoc');
			 if(!empty($_POST['bakURL']))
			    $this->assign('jumpUrl', str_replace(array('~','_'),array('?','/'), urldecode($_POST['bakURL'])));
			 $m->save($_POST);	
			 //dump($_POST);		 
			 //cho str_replace(array('~','_'),array('?','/'), urldecode($_POST['bakURL']));
			 $this->success('修改成功');
		  }
	  }	  
  }

  //目前搞掂不了反斜杠的问题，以下做法就是再读一次文件，十分愚蠢
  public function insert() {
    $rt = array();
    $url = array(
      0=>array(
        doc=>'E:\\www\admin_doc',
        temp=>"E:\\www\\admin_temp_doc",
        complete=>"E:\\www\\admin_complete"
      ),
      1=>array(
        doc=>'f:/doc',
        temp=>"F:/temp_doc",
        complete=>"f:/admin_complete"
      )
    );
    $urls = $url[$this->_dev];
    $urlTempDoc = $urls['temp'];
    //$type = array(0=>"doc,docx",1=>"ppt,pptx",2=>"xls,xlsx",3=>"pot,potx",4=>"pps",5=>"vsd",6=>"pub",7=>"mpp",8=>"rtf",9=>"pdf",10=>"txt");
    $d = dir($urlTempDoc);
    $m = M();
    while(FALSE !== ($item = $d->read())) {
      if('.' ==$item || '..'==$item) {
        continue;
      }
      if(is_file($urlTempDoc . '/' .$item)) {
        $filesize = filesize($urlTempDoc . '/' .$item);
        copy($urlTempDoc . '/' .$item,$urls['doc']."\\".$item); //拷贝到新目录
        unlink($urlTempDoc . '/' .$item); //删除旧目录下的文件
        $item = mysql_escape_string(mb_convert_encoding($item,'utf-8','gbk'));
        $docName	= $urls['doc'].'\\'.$item;
        $title  = explode(".", $item);
        $title = $title[0];
        $docName = str_replace("\\", "\\\\", $docName);
        $sql = "select * from a_doc where file_url like '%$item%'";
        $list = $m->query($sql);
        if ($list) {
          $sql = "update a_doc set file_url = '$docName' where id = ".$list[0]["id"];
          $m->execute($sql);
          //用户上传的文档
        }else {
          //管理员上传的文档
          $sql = "insert into a_doc (title,file_url,file_info,file_size,owner_id,owner_name,ischeck) values ('$title','$docName','$title','$filesize',1,'admin',1)";
          $m->execute($sql);
        }

      }
    }
    $this->ajaxReturn('成功');
  }

  public function insertType() {
    $ids = implode(',', $_POST['ids']);
    //$_POST["hy_id"];
    $m = M();
    $sql = "update a_doc set hy_id = ".$_POST["hy_id"].", zy_id = ".$_POST["zy_id"]." where id in (".$ids.")";
    $m->execute($sql);
    $this->ajaxReturn("成功");
  }


  public function createBat() {
    $this->display("create-bat");
  }

  //更新fileswf_file_name,ischeck,add_time字段
  public function ajaxCreateBat() {
    $dev = $this->_dev;
    $date = date("Y-m-d");
    $flagUrl = array(
      0 => array(
        doc=>'E:\www\admin_doc',
        swf=>"E:\www\admin_swf\\".$date,
        complete=>"E:\www\admin_complete\\".$date,
        printer=>"\"C:\Program Files\Macromedia\FlashPaper 2\FlashPrinter.exe\"",
        bat=>"E:\www\admin_doc\create_swf".$date.".bat"
      ),
      1 => array(
        doc=>'f:/doc',
        swf=>"f:/admin_swf".$date,
        complete=>"f:/admin_complete".$date,
        printer=>"\"C:\Program Files\Macromedia\FlashPaper 2\FlashPrinter.exe\"",
        bat=>"f:/create_swf".$date.".bat"
      )
    );
    $urls = $flagUrl[$dev];
    $urlDoc = $urls["doc"];
    $urlBat = $urls['bat'];
    $batStr = "mkdir ".$urls['swf']."\r\n"." mkdir ".$urls["complete"]."\r\n ";
    $d=dir($urlDoc);
    $rt = array();
    while(FALSE !== ($item = $d->read())) {
      if('.' ==$item || '..'==$item) {
        continue;
      }
      if(is_file($urlDoc.'/'.$item)) {
        $doc_name	= $urlDoc.'\\'.$item;
        $swf_file_name = time().rand(1000,9999);
        //$fileUrl = $urls['complete']."\\".$swf_file_name.".swf";
        //$fileUrl = str_replace('\\', '\\\\', $fileUrl);
        $suffix = explode('.', $item);
        $suffix = $suffix[1];
        $swf_name	= $urls["swf"]."\\".$swf_file_name;
        $complete_name = $urls["complete"]. '\\' .$swf_file_name.".".$suffix;
        $add_time = time();
        $m = M();
        if($doc_name!="$urlDoc\create_swf.bat") {
          $bat_conntent	='';
		  $bat_conntent.="move \"$doc_name\"  \"$complete_name\" "."\r\n";
          $bat_conntent.= $urls["printer"]." -o \"$swf_name.swf\" \"$complete_name\""."\r\n";          
          $name = mysql_escape_string(mb_convert_encoding($item,'utf-8','gbk'));

          //$sql = "select id from a_doc where ischeck = 0 and isswf = 0 and file_url like '%".$name."%' order by id desc limit 1";
          $sql = "select id from a_doc where isswf = 0 and (ischeck = 0 or (owner_id=1 and ischeck=1)) and file_url like '%".$name."%' order by id desc limit 1";
          $count = $m->query($sql);
          $id = $count[0]['id'];
          if (!$id) {
            $rt[] = $name."这个文件出错，请删掉再从新操作一次";
          }else {
            $sql = "update s464866db0.a_doc set file_url = '".str_replace('\\', '\\\\', $complete_name)."',swf_file_name='".$swf_file_name."',isswf=1,add_time = '".$add_time."' where id=$id";
            $conn = "mysql -h124.172.234.208 -us464866db0 -p368b9vn9 -e\"$sql \";"."\r\n";
            if ($dev == 1) $conn = "mysql -hlocalhost -uroot -proot -e\"$sql \";"."\r\n";
            //$bat_conntent.="mysql -h124.172.234.208 -us464866db0 -p368b9vn9 -e$command_str;"."\r\n";
            $bat_conntent .= $conn;
            $batStr .= $bat_conntent;
          }
        }
      }

    }
    //$batStr .= "del /Q $urlBat";
    if(file_put_contents($urlBat,$batStr)) {
      $this->ajaxReturn("成功");
    }else {
      $this->ajaxReturn("生成失败");
    }
  }


  public function userDoc() {
    $m = M("ADoc");
    import("@.ORG.Page"); //导入分页类
    $records = 10;//每页多少条记录
    $count = $m->where('isswf = 1 and ischeck = 0 and owner_id > 1')->count();
    $p = new Page ($count,$records);
    $p->setConfig('header','篇记录');
    $p->setConfig('prev',"上一页");
    $p->setConfig('next','下一页');
    $p->setConfig('first','<<');
    $p->setConfig('last','>>');
    $page = $p->show ();
    $sql = "select id,title,file_url,from_unixtime(add_time) as add_time from a_doc where isswf = 1 and ischeck = 0 and owner_id > 1 limit ".$p->firstRow.','.$p->listRows;
    $list = $m->query($sql);
    $this->assign('dev',$this->_dev);
    $this->assign("info", $list);
    $this->assign("nowPage",$p->nowPage);
    $this->assign("page", $page );
    $this->assign("records",$records);
    $this->display('user-doc');
  }

  public function ajaxDeleteUserRecord() {
    $m = M('ADoc');
    $url = $m->field('file_url')->where("id=".$_POST['id'])->select();
    $urlComplete = $url[0]['file_url'];
    $urlSwf = str_replace('complete', 'swf', $urlComplete);
    $prefix = explode('.', $urlSwf);
    $urlSwf = $prefix[0].".swf";
    unlink($urlComplete);//删了admin_complete下的对应文档
    unlink($urlSwf);//删了admin_swf下的对应文档
    $m->where("id=".$_POST["id"])->delete();
    $this->ajaxReturn("删除成功");
  }

  public function ajaxPreviewUserRecord() {
    $id = $_POST["id"];
    $m = M("ADoc");
    $list = $m->where("id=$id")->find();
    $url = str_replace('complete', 'swf', $list["file_url"]);
    $url = ($this->_dev == 1)?substr($url, 22):substr($url, 16);
    $prefix = explode('.', $url);
    $url = $prefix[0].".swf";
    $this->ajaxReturn($url);
  }

  public function ajaxPassUserRecord() {
    $id = $_POST['id'];
    $m = M();
    $sql = "update a_doc set ischeck = 1 where id = $id";
    $m->execute($sql);
    $this->ajaxReturn($id);

  }
/*
  public function initFileUrl(){
    echo "初始化开始";
    $m = M();
    $list = $m->query("select * from a_doc where file_url  like '%wampwww%'");
    foreach($list as $k => $l){
      $str = explode('\\', $l['file_url']);
      $name = $str[count($str)-1];
      $fileUrl = "E:\\\\www\\\\admin_complete\\\\2011-04-10\\\\".$name;
      if ($this->_dev == 1) $fileUrl = "D:\\\\wamp\\\\www\\\\admin_complete\\\\2011-04-10\\\\".$name;
      $sql = "update a_doc set file_url = '".$fileUrl."' where id=".$l['id'];
      $m->execute($sql);
    }
  } */


/****************************************/
/*            似有方法开始                 */
/*                                       */
/*************************************** */
    /*
  *    获取行业列表
  */
  private function _getHyList(){
	 $m = M('AHy');
	 $first =  $m->where('type=1')->select();
	 foreach($first as &$fir){
		$kids = $m->where('did='.$fir['id'])->select(); 
		$fir['kids'] = $kids;
	 }
	 return $first;	  
  }

  /*
  *    获取专业列表
  */  
  private function _getZyList(){
	 $m = M('AZy');
	 $first =  $m->where('type=2 and id>149')->select();
	 foreach($first as &$fir){
		$kids = $m->where('did='.$fir['id'])->select(); 
		$fir['kids'] = $kids;
	 }
	 return $first;		  
  }
  
  /*
  *  获取地区列表
  */
  private function _getDqList(){
	$m = M('ARegion');
	$first = $m->where('did=0')->order('px DESC,ID ASC')->select();
	foreach($first as &$fir){
		$second = $m->where('did='.$fir['id'])->order('title ASC')->select();
		$fir['kids'] = $second;		
	}
	return $first; 
  }
  
  private function _getAppList(){
	 $m = M('ALawApptype');
	 $list = $m->order('sort ASC')->select();
	 return $list;  
  }
  
  private function _getTypeList(){
	 $m = M('ADocType');
	 $list = $m->order('sort ASC')->select();
	 return $list;	  
  }
  
}
?>